<template>
  <th class="data-upload-preview-table-title-row">
    <!-- 字段名称 -->
    <div class="field-name-wrapper" :class="{'border-danger': editError}">
      <input type="text" v-focus="fieldNameFocus" v-model="name" @focus="selfFocus" @blur="selfBlur">
      <i class="iconfont icon-editor" v-if="!fieldNameFocus" @mousedown.stop="editFieldName"></i>
      <i class="iconfont icon-check" v-if="fieldNameFocus" @mousedown.stop="editFieldNameEnd"></i>
    </div>

    <!-- 字段类型 -->
    <div class="field-type-wrapper">
      <div class="field-type">
        <!-- <span>{{ types.get(fieldType) }}</span> -->
        <span>{{ fieldTypeTip }}</span>
        <!-- <i class="iconfont" :class="currentField === fieldName ? 'icon-arrow-down':'icon-arrow-up'" @click="toggleField" @blur="typeBlur" tabindex="6"></i> -->
      </div>
      <!-- 修改字段类型下拉菜单 -->
      <!-- <div class="menu-container">
			<div class="menu create-index" v-if="true">
				<span>建立索引</span>
			</div>
		</div> -->
      <!-- <div class="menu-container" >
			<div class="menu" v-show="currentField === fieldName">
				<h6 v-for="(field,index) of fieldTypes" :key="index" @click="selectFiledType(field)">{{field.type}}</h6>
			</div>
		</div> -->
    </div>
  </th>
</template>

<script>
  import Bus from '../../utils/event_bus'
  // const typeMap = new Map([
  // 	['text', '文本'], ['long', '整数'], ['integer', '整数'], ['double', '小数'],
  // 	['date', '日期'], ['boolean', '布尔型'], ['timestamp', '日期']
  // ]);

  export default {
    name: 'data-upload-preview-table-title-row',
    props: {
      fieldIndex: Number,
      fieldName: String,
      fieldType: String,
      toSubmitFields: Array,
      currentField: String,
    },

    data() {
      const illegalField = ['_id', 'the_geom', 'the_geom_webmercator'];
      const fieldTypes = [{
          value: ['text', 'character'],
          type: '文本'
        },
        {
          value: ['timestamp without time zone', 'timestamp', 'date', 'time'],
          type: '日期'
        },
        {
          value: ['bigint', 'integer', 'long'],
          type: '整数'
        },
        {
          value: ['double precision', 'float', 'numeric', 'double'],
          type: '小数'
        },
      ];
      return {
        // types: typeMap,
        fieldNameFocus: false,
        name: this.fieldName,
        type: this.fieldType,
        // validNamePattern: /^[-_a-zA-Z0-9\u4e00-\u9fa5]+$/,
        invalidChar: /[A-Z\%\~\`\!\！\@\#\$\^\&\*\(\（\)\）\{\}\[\]\;\:\"\'\\\/\?\>\.\<\《\》\,\=\|\、\，\。\？]+/g,
        editError: false,
        i: 1,
        fieldTypes,
        fieldsSelectType: '', //修改的文本类型
        illegalField
      };
    },
    computed: {
      fieldTypeTip() {
        let fieldTypeTip = '文本';
        this.fieldTypes.map(
          (val) => {
            if (val.value.includes(this.fieldType)) {
              fieldTypeTip = val.type;
            }
            return;
          }
        )
        return this.fieldsSelectType ? this.fieldsSelectType : fieldTypeTip;
      }
    },
    methods: {
      editFieldName() {
        if (!this.fieldNameFocus) {
          this.fieldNameFocus = true;
        }
      },
      editFieldNameEnd() {
        if (this.fieldNameFocus) {
          this.changeFieldName();
        }
      },
      selfFocus() {
        if (!this.fieldNameFocus) {
          this.fieldNameFocus = true;
        }
      },
      selfBlur() {
        if (this.fieldNameFocus) {
          this.changeFieldName();
        }
      },
      changeFieldName() {
        // 字段名为空，提示错误
        if (this.name === '') {
          this.$message.error('字段名不能为空');
          this.fieldNameFocus = false;
          Bus.$emit('duplicate-column-name');
          this.editError = true;
          return;
        }
        if (this.illegalField.includes(this.name)) {
          this.$message.error(`${this.name}为保留字段`);
          this.fieldNameFocus = false;
          Bus.$emit('duplicate-column-name');
          this.editError = true;
          return;
        }
        // 判断是否出现同名字段
        let existIdx = this.toSubmitFields.lastIndexOf(this.name);
        this.fieldNameFocus = false;
        if (existIdx != -1 && existIdx != this.fieldIndex) {
          this.$message.error('存在同名字段');
          Bus.$emit('duplicate-column-name');
          this.editError = true;
          return;
        }
        this.editError = false;
        // 若没有出现错误，触发改字段事件
        Bus.$emit('field-name-change', this.fieldIndex, this.name);
      },

      // 检查字段名称是否包含非法字符
      checkName() {
        return this.invalidChar.test(this.name);
      },

      selectFiledType(field) {
        this.fieldsSelectType = field.type;
        Bus.$emit('field-type-change', this.fieldIndex, field.value[0]);
        this.closeField();
      },

      typeBlur() {
        let self = this;
        setTimeout(() => {
          self.closeField();
        }, 300)
      },

      toggleField() {
        let field = this.currentField === this.fieldName ? '' : this.fieldName;
        this.$emit('set-current-field', field);
      },

      closeField() {
        this.$emit('set-current-field', '');
      }

    },

    created() {
      if (this.checkName()) {
        // this.name = this.name.replace(this.invalidChar, '_');
        Bus.$emit('field-name-change', this.fieldIndex, this.name);
        return;
      }
    },

    watch: {
      fieldName() {
        this.name = this.fieldName;
      },
      name(oldVal, newVal) {
        if (this.name === '') {
          return;
        }
        if (this.checkName()) {
          this.name = this.name.replace(this.invalidChar, '_');
          Bus.$emit('field-name-change', this.fieldIndex, this.name);
          return;
        }
        if (!this.fieldNameFocus) {
          return;
        }
      },
      type() {
        Bus.$emit('field-type-change', this.fieldIndex, this.type);
      }
    },

    directives: {
      focus: {
        update(el, {
          value
        }) {
          if (value) {
            el.focus();
          }
        }
      }
    }
  }

</script>

<style lang="scss" scoped>
  @import "common";

  .data-upload-preview-table-title-row {
    white-space: nowrap;
    text-align: left;
    padding: 0 8px;
    height: 32px;
    line-height: 32px;
    white-space: nowrap;
    border: 1px solid $bdGray;
    min-width: 100px;
    max-width: 280px;

    .border-danger {
      >input {
        border: 1px solid rgba(255, 0, 0, 0.5);
      }
    }

    .field-name-wrapper {
      position: relative;
      line-height: 28px;

      >input {
        width: calc(100% - 28px);
        padding: 2px;
        text-overflow: ellipsis;
        background: #f6f8fb;
        font-size: 12px;
      }

      >i {
        font-size: 12px;
        opacity: 50;
        margin-left: 5px;
        position: absolute;

        &.icon-up-down {
          color: rgba(0, 0, 0, 0.3);
        }

        &.icon-editor,
        &.icon-check {
          color: #ccc;
          right: 0px;
        }

        &.icon-check {
          font-size: 14px;
        }

        &:hover {
          color: #58B7FF;
          cursor: pointer;
        }

      }
    }

    .field-type-wrapper {
      position: relative;
      line-height: 28px;

      .field-type {
        color: #ccc;
        margin-top: -8px;
        padding: 2px;

        span {
          font-size: 10px;
        }

        >i {
          font-size: 12px;
          opacity: 50;
          margin-left: 5px;
          float: right;
          outline: none;

          &:hover {
            color: #58B7FF;
            cursor: pointer;
          }

        }

      }

      // .menu-container {

      // 	position: relative;

      // 	.menu {
      // 		position: absolute;
      // 		color: #58B7FF;
      // 		background-color: #fff;
      // 		box-shadow: 0 8px 16px 0 rgba(0, 0, 0, 0.1);
      // 		border-radius: 3px;
      // 		z-index: 10;
      // 		right: -10px;
      // 		top: -24px;
      // 		width: 80px;
      // 		height: 30px;
      // 		font-size: 12px;
      // 		text-align: center;

      // 		&:hover {
      // 			cursor: pointer;
      // 		}

      // 		span {
      // 			line-height: 30px;
      // 		}
      // 	}
      // }
      .menu-container {

        position: relative;
        outline: none;

        .menu {
          position: absolute;
          background-color: #fff;
          box-shadow: 0 8px 16px 0 rgba(0, 0, 0, 0.1);
          border-radius: 3px;
          z-index: 10;
          right: -10px;
          width: 80px;
          font-size: 12px;
          text-align: center;

          &:hover {
            cursor: pointer;
          }

          span {
            line-height: 30px;
          }

          h6 {
            color: #ccc;

            &:hover {
              color: #58B7FF;
              background-color: $bdGray;
            }
          }
        }
      }
    }

  }

</style>
